/**
 * Copyright (C) 2024
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */

import __config from "@/config/env"; // 配置文件
import service from "@/store/service"; //存储相关数据服务util
const scope = "server"; //登录时使用

const request = (url, method, data, showLoading) => {
	let _url = url;
	// #ifdef APP || MP
	_url = __config.basePath + url;
	// #endif
	let access_token = getApp() ? getApp().globalData.access_token : '';
	let expires_in = getApp() ? getApp().globalData.expires_in : ''; //过期时间
	// #ifdef MP
	// 小程序如果登录过重新打开时getApp获取不到,这里处理一下
	if (!getApp()) {
		const loginTokenInfo = service.getLoginAccessToken();
		if (!access_token) {
			access_token = loginTokenInfo.access_token;
		}
		if (!expires_in) {
			expires_in = loginTokenInfo.expires_in;
		}
	}
	// #endif
	return new Promise((resolve, reject) => {
		if (!access_token) {
			//没有跳转登录
			service.removeRefreshToken();
			// uni.showToast({
			// 	icon: 'none',
			// 	position: 'bottom',
			// 	title: '身份验证信息已失效,请重新登录'
			// });
			uni.reLaunch({
				url: "/pages/login/login",
			});
			reject();
			return;
		}
		const curDateTime = new Date().getTime() + 3000; // 当前时间提前3秒验证token过期时间
		if (curDateTime > expires_in) {
			// 如果当前时间大于token过期时间表示token已过期需要重新刷新token
			// token过期，刷新token
			refreshToken()
				.then((response) => {
					access_token = response.access_token;
				})
				.catch((response) => {
					//失败 重新登录
					uni.hideLoading();
					reject();
					return;
				});
		}
		if (showLoading) {
			uni.showLoading({
				title: "加载中",
			});
		}
		uni.request({
			url: _url,
			method: method,
			data: data,
			withCredentials: true,
			header: {
				Authorization: "Bearer " + access_token,
				"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
			},
			success(res) {
				uni.hideLoading();
				if (res.statusCode == 200) {
					if (res.data.code != 0) {
						if (res.data.code == 60001) {
							// session过期，则清除过期session，并重新加载
							// token过期，刷新token
							refreshToken()
								.then((response) => {
									uni.showModal({
										title: "提示",
										content: "出了点小差错，请重试一下～",
										success() {},
										complete() {},
									});
									reject("session过期");
								})
								.catch((response) => {
									//失败 重新登录
									reject("session过期请重新登录");
									return;
								});
						} else if (res.data.code == 20001) {
							//兼容getui返回
							resolve(res.data);
						} else if (res.data.errCode != 0) {
							let errMsg = res.data.msg || res.errMsg;
							uni.showModal({
								title: "提示",
								content: res.data.msg + "",
								success() {},
								complete() {},
							});
							reject(res.data.msg);
						} else {
							//兼容im返回
							resolve(res.data);
						}
					}
					resolve(res.data);
				} else if (res.statusCode == 401 || res.statusCode == 426) {
					service.removeUser();
					// 跳转到登录
					uni.reLaunch({
						url: "/pages/login/login",
					});
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: response.msg,
					});
				} else if (res.statusCode == 404) {
					uni.showModal({
						title: "提示",
						content: "接口请求出错，请检查手机网络",
						success(res) {},
					});
					reject();
				} else {
					console.log(res);
					uni.showModal({
						title: "提示",
						content: res.data.msg + "",
						success(res) {},
					});
					reject();
				}
			},
			fail(error) {
				console.log("error");
				uni.hideLoading();
				if (error.errMsg && error.errMsg.indexOf("statusCode:-1") != -1) {
					console.log("无网络");
				} else {
					uni.showModal({
						title: "提示",
						content: "接口请求出错：" + error.errMsg,
						success(res) {},
					});
				}
				reject(error);
			},
			complete(res) {
				uni.hideLoading();
			},
		});
	});
};

// 不需要验证的接口，如登录时的接口
const requestNotValidate = (url, method, data, showLoading = false, headers = {}) => {
	let _url = url;
	// #ifdef APP || MP
	_url = __config.basePath + url;
	// #endif
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				title: "加载中",
			});
		}
		uni.request({
			url: _url,
			method: method,
			data: data,
			withCredentials: true,
			header: {
				isToken: false,
				Authorization: "Basic YWRtaW46YWRtaW4=",
				"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
				...headers,
			},
			success(res) {
				uni.hideLoading();
				if (res.statusCode == 200) {
					resolve(res.data);
				} else if (res.statusCode == 404) {
					uni.showModal({
						title: "提示",
						content: "接口请求出错，请检查手机网络",
						success(res) {},
					});
					reject();
				} else if (res.statusCode == 401 || res.statusCode == 426) {
					service.removeUser();
					uni.showToast({
						title: res.data.msg,
						icon: "none",
					});
					reject(res.data);
				} else {
					let errMsg = res.data ? res.data.msg : res.errMsg
					uni.showModal({
						title: "提示",
						content: errMsg,
						success(res) {},
					});
					reject();
				}
			},
			fail(error) {
				console.log(error);
				uni.hideLoading();
				uni.showModal({
					title: "提示",
					content: "接口请求出错：" + error.errMsg,
					success(res) {},
				});
				reject(error);
			},
			complete(res) {
				uni.hideLoading();
			},
		});
	});
};

// 刷新token
const refreshToken = () => {
	// token过期，刷新token
	const refresh_token = service.getRefreshToken();
	const grant_type = "refresh_token";
	const query = "?refresh_token=" + refresh_token + "&grant_type=" + grant_type + "&scope=" + scope;
	return new Promise((resolve, reject) => {
		requestNotValidate("/auth/oauth/token" + query, "POST", null, false)
			.then((response) => {
				// 登录成功 保存登录数据、本次登录的token
				service.saveAccessToken(response, getApp().globalData);
				resolve(response);
			})
			.catch((response) => {
				//失败 重新登录
				service.removeRefreshToken();
				uni.showToast({
					icon: "none",
					position: "bottom",
					title: "身份验证信息已失效,请重新登录",
				});
				uni.reLaunch({
					url: "/pages/login/login",
				});
				reject();
			});
	});
};


/**
 * 上传文件接口
 * @param {Object} filePath 本地文件路径
 * @param {Object} dir 上传保存的文件目录, 如头像保存的目录: headimg/
 * @param {Object} fileType 文件类型
 */
export function uploadFile(filePath, dir, fileType) {
	let access_token = getApp().globalData.access_token;
	// 上传文件
	let _url = '/upms/file/upload?fileType=' + fileType + '&dir=' + dir;
	//#ifndef H5
	_url = __config.basePath + _url;
	//#endif
	return new Promise((resolve, reject) => {
		if (!access_token) {
			//没有跳转登录
			service.removeRefreshToken();
			uni.reLaunch({
				url: "/pages/login/login",
			});
			reject();
			return;
		}
		uni.uploadFile({
			url: _url,
			filePath: filePath,
			name: 'file',
			formData: {
				fileType: fileType,
				dir: dir
			},
			header: {
				Authorization: "Bearer " + access_token,
				"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
			},
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == '200') {
					let link = JSON.parse(uploadFileRes.data).link;
					resolve(link)
				} else {
					uni.showModal({
						title: this.$t('commons.tip'),
						content: this.$t('commons.uploadFail') + uploadFileRes.data,
						success(res) {}
					});
					reject()
				}
			},
			fail: (err) => {
				console.log(err);
				reject()
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	})
}

export default {
	request: (obj) => {
		// obj : {  //obj对象传进来的数据格式
		// 	url: '/mall/orderitem/page',
		// 	method: 'get',
		// 	params: query,
		// 	data: obj
		// }
		let url = obj.url; // 拼接query参数
		if (obj.params) {
			if (obj.params instanceof Object) {
				let p = [];
				for (let key in obj.params) {
					let t = key + "=" + obj.params[key];
					p.push(t);
				}
				url = obj.url + "?" + p.join("&");
			} else {
				url = obj.url + obj.params;
			}
		}
		return request(url, obj.method.toUpperCase(), obj.data, obj.showLoading ? obj.showLoading : false);
	},
	/**
	 * 新的请求方式,方便快速复制后台接口ts文件开发
	 */
	requestNew: (method, url, postData, showLoading) => {
		// let url = obj.url; // 拼接query参数
		let data = postData ? postData.data : null;
		if (postData && postData.params) {
			if (postData.params instanceof Object) {
				let p = [];
				for (let key in postData.params) {
					let t = key + "=" + postData.params[key];
					p.push(t);
				}
				url = url + "?" + p.join("&");
			} else {
				url = url + postData.params;
			}
		}
		return request(url, method.toUpperCase(), data, showLoading ? showLoading : false);
	},
	requestValidate: request,
	requestNotValidate,
	login: {
		// 登录接口
		randomStr: __config.basePath + "/code?randomStr=", // 获取验证码
		loginByUsername: (user) => {
			const grant_type = "password";
			const password = encodeURIComponent(user.password); // 密码需要编码
			const query = "?username=" + user.username + "&password=" + password + "&randomStr=" + user.randomStr +
				"&code=" + user.code + "&grant_type=" + grant_type + "&scope=" + scope;
			return requestNotValidate("/auth/oauth2/token" + query, "POST", null, true);
		},
		refreshToken: (refresh_token) => {
			const grant_type = "refresh_token";
			const query = "?refresh_token=" + refresh_token + "&grant_type=" + grant_type + "&scope=" + scope;
			return requestNotValidate("/auth/oauth2/token" + query, "POST", null, false);
		},
		loginByPhone: (phone, code) => {
			const grant_type = "sms_login";
			const query = "?phone=" + phone + "&code=" + code + "&grant_type=" + grant_type;
			return requestNotValidate("/auth/phone/token/sms" + query, "POST", null, true);
		},
		loginByThirdParty: (type, code) => {
			return requestNotValidate(
				"/auth/thirdparty/token",
				"POST", {
					thirdparty: type + "@" + code,
				},
				true
			);
		},
		sendCode: (data) => {
			const query = "?phone=" + data.phone + "&type=" + data.type + "&graphCode=" + data.graphCode;
			return requestNotValidate("/upms/phone/code" + query, "PUT", data, true);
		},
	},
	getUserInfo: (data) => {
		return request("/upms/user/info", "GET", data, false);
	},
	logout: (data) => {
		return request("/auth/token/logout", "DELETE", data, true);
	},
	register: (data) => {
		return request("/upms/user/register", "POST", data, true);
	},
	mall: {
		// 快递公司
		orderlogistics: (data) => {
			return request("/mall/configlogistics/logisticscompany", "GET", data, false);
		},
		// 店铺快递月结账号
		shoplogisticsaccount: (shopId, logisticsCode) => {
			return request(`/mall/shoplogisticsaccount/list?shopId=${shopId}&logisticsCode=${logisticsCode}`, "GET", null, false);
		},
		imLogin: (data) => {
			//im 登录
			return request("/mall/im/login", "POST", data, false);
		},
		imRegister: (data) => {
			//im 注册
			return request("/mall/im/register", "POST", data, false);
		},
		getuiAliasBind: (data) => {
			//个推绑定别名
			return request("/mall/getui/alias/bind", "POST", data, false);
		},
		getuiAliasGet: (cid) => {
			//根据cid查询别名
			return request("/mall/getui/alias/" + cid, "GET", null, false);
		},
	},
};